<?php

namespace App\Admin\Models;

use App\Admin\Models\SystemModel;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;

class WorshipHymn extends Model
{
    use SoftDeletes;

    protected $guarded = []; 

    public function __construct(){
        parent::__construct();
        $this->mergeCasts(SystemModel::fieldCasts($this->getTable()));
    }

    public function albums()
    {
        return $this->belongsToMany(
            WorshipAlbum::class,
            'worship_hymn_album',
            'hymn_id',
            'album_id'
        );
    }

    public function artists()
    {
        return $this->belongsToMany(
            WorshipArtist::class,
            'worship_hymn_artist',
            'hymn_id',
            'artist_id'
        );
    }

    public function mp3()
    {
        return $this->hasOne(
            SystemMedia::class,
            'id',
            'mp3'
        );
    }

    public function lyric()
    {
        return $this->hasOne(
            SystemMedia::class,
            'id',
            'lyric'
        );
    }

    public function formaContent($content)
    {
        $contents = array_filter(explode('#', $content));
        return str_replace("\n", "<br/>", implode($contents));
    }

    public function formaLyric($lyric)
    {
        return str_replace("\n", "<br/>", $lyric);
    }

    public function spectrums($arr)
    {
        if (!is_array($arr)) $arr = [$arr];
        if (!empty($arr)){
            $string = implode(',', $arr);
            return SystemMedia::whereIn('id', $arr)
                ->orderByRaw(DB::raw("FIELD(id, $string)"))
                ->get(['id','origin_filename','path']);
        } else {
            return [];
        }
    }
}
